package com.example.LibrarySystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.LibrarySystem.annotation.RoleAnnotation;
import com.example.LibrarySystem.mapper.ClassesMapper;
import com.example.LibrarySystem.pojo.Classes;
import com.example.LibrarySystem.pojo.User;
import com.example.LibrarySystem.response.Result;
import com.example.LibrarySystem.service.ClassesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/classes")
@Transactional
public class ClassesController {

    @Autowired
    private ClassesService classesService;

    @Autowired
    private ClassesMapper classesMapper;

    /**
     * 添加一个班级
     *
     * @param classes
     * @return
     */
    @PostMapping("/insert")
    @RoleAnnotation(type = "admin")
    public Result insert(@RequestBody Classes classes) {
        // 三目运算:  条件  ?  true 执行这里 : false 执行这里
        return classesService.insert(classes) > 0 ? new Result("添加成功", 200) : new Result("添加失败", -1);
    }

    /**
     * 根据id 删除班级
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @RoleAnnotation(type = "admin")
    public Result deleteById(@PathVariable Integer id) {
        int res = classesMapper.delById(id);
        if (res > 0) {
            return new Result("删除成功", 200);
        }
        return new Result("删除失败请重试", -1);
    }

    /**
     * 查询所有班级(条件分页)
     */
    @GetMapping("/getClassesByAll")
    @RoleAnnotation(type = "admin")
    public Result getClassesByAll(@RequestParam Map<String, String> data) {
        IPage<Classes> classesByAll = classesService.getClassesByAll(data);

        Result result = new Result();
        result.put("data",classesByAll.getRecords());
        result.put("size",classesByAll.getSize());
        result.put("total",classesByAll.getTotal());
        return result;
    }


    /**
     * 修改一个班级
     * @param classes
     * @return Result
     */
    @PostMapping("/update")
    @RoleAnnotation(type = "admin")
    public Result updateClassesById(@RequestBody Classes classes){
        QueryWrapper<Classes> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",classes.getId());
        int res = classesMapper.update(classes, queryWrapper);
        if (res > 0) {
            return new Result("修改成功", 200);
        }
        return new Result("修改失败请重试", -1);
    }
}
